/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import java.sql.*;
import java.util.*;
import DTO.clsPhongBan;

/**
 *
 * @author XuanHung
 */
public class PhongBanDAO {
    Statement st;
    ResultSet rs;
    Datacontact dct = new Datacontact();
    
    public ArrayList<clsPhongBan> getData() throws Exception{
       ArrayList <clsPhongBan> dspb = new ArrayList<>();
       try{
           st = dct.getM_conn().createStatement();
           String strSQL = "select * from PhongBan";
           clsPhongBan phongban;
           rs = st.executeQuery(strSQL);
           while(rs.next()){
               phongban = new clsPhongBan(rs.getInt("MaPhongBan"), rs.getString("tenPhongBan"), rs.getShort("TruongPhong"));
               dspb.add(phongban);
           }
       }
       catch (Exception ex){
           throw new Exception(ex.toString());
       }
        return dspb;
    }
    public boolean xoaPhongBan(clsPhongBan pb) throws Exception{
        boolean bEqual = false;
        String strSQL = "DELETE FROM phongban WHERE maphongban = '"+pb.getM_iMaPhongBan()+"'";
        try{
            st = dct.getM_conn().createStatement();
            st.executeQuery(strSQL);
            bEqual = true;
        }
        catch(Exception ex){
            throw new Exception(ex.toString());
        }
        return bEqual;                
    }
    public boolean luuPhongBan(clsPhongBan pb, boolean bUpdate) throws SQLException{
        boolean bEqual = false;
        String strSQL;
        strSQL = "";
        PreparedStatement ps = null;
        int iMaPhongBan = pb.getM_iMaPhongBan();
        String strTenPhong = pb.getM_strTenPhong();
        int iTruongPhong = pb.getM_iTruongPhong();
        
        if(bUpdate == false){
            strSQL = "INSERT INTO phongban(MaPhongBan, TenPhongBan, TruongPhong) VALUES (?,?,?)";
            ps = dct.getM_conn().prepareStatement(strSQL);
            ps.setInt(1, iMaPhongBan);
            ps.setString(2, strTenPhong);
            ps.setInt(3, iTruongPhong);         
        }
        else{
            strSQL = "UPDATE phongban SET TenPhongBan= ?, TruongPhong = ? WHERE MaPhongBan = ?";
            ps = dct.getM_conn().prepareCall(strSQL);
            ps.setInt(3, iMaPhongBan);
            ps.setString(1, strTenPhong);
            ps.setInt(2, iTruongPhong);
        }
        if(ps.executeUpdate()== 1){
            bEqual = true;
        }
        return bEqual;
    }
}
